package com.tuerks.sbahn;

import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.format.Time;
import android.util.Log;
import android.widget.RemoteViews;

public class WidgetProvider extends AppWidgetProvider {
	private static final String LOG_TAG = "ImagesWidgetProvider";

	public static final String URI_SCHEME = "images_widget";

	@Override
	public void onEnabled(Context context) {
		// This is only called once, regardless of the number of widgets of this
		// type
		// We do not have any global initialization
		Log.i(LOG_TAG, "onEnabled()");
		super.onEnabled(context);
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		Log.d(LOG_TAG, "onUpdate(): ");

		for (int appWidgetId : appWidgetIds) {

			String[][] schedule = null;
			String query;
			Time queryTime = new Time();
			queryTime.set(System.currentTimeMillis() - 600000);
			String col1 = new String();
			String col2 = new String();
			String col3 = new String();
			String col4 = new String();
			String col5 = new String();
			String widgetHeader = new String();

			Date date1 = new Date();
			Date currentDate = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat();
			currentDate.setTime(System.currentTimeMillis());

			// Create an Intent to launch MainActivity
			// Intent intent = new Intent(context, MainActivity.class);

			SharedPreferences sharedPrefs = PreferenceManager
					.getDefaultSharedPreferences(context);
			SharedPreferences config = context.getSharedPreferences(
					WidgetConfiguration.PREFS_NAME, 0);
			String station = config.getString(String.format(
					WidgetConfiguration.PREFS_UPDATE_STATION_FIELD_PATTERN,
					appWidgetId), "");
			Log.v("s-bahn in widget read station from prefs", station);
			Uri uri = null;
			uri = Uri.parse("http://www.tuerks.com/?station=" + station);
			Intent intent = new Intent("MAIN", uri, context,
					ShowStationActivity.class);
			intent.putExtra("station", station);
			PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
					intent, 0);

			RemoteViews remoteView = new RemoteViews(context.getPackageName(),
					R.layout.widget);
			remoteView.setOnClickPendingIntent(R.id.linearLayout1,
					pendingIntent);

			Log.i("station", "x=" + station);
			query = "http://s-bahn-muenchen.hafas.de/bin/stboard.exe/dn?L=&widget=yes&input="
					+ station
					+ "&boardType=dep&time="
					+ queryTime.format("%H:%M")
					+ "&productsFilter=000010000000&additionalTime=0&disableEquivs=yes&maxJourneys="
					+ sharedPrefs.getString("rows", "30")
					+ "&outputMode=undefined&start=yes&selectDate=today&monitor=1&requestType=0";

			try {
				widgetHeader = URLDecoder.decode(station).substring(0,
						URLDecoder.decode(station).indexOf("#"));
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				String readSbahnFeed = SbahnUtil.readSbahnFeed(query);
				readSbahnFeed = readSbahnFeed
						.replaceFirst("journeysObj = ", "");
				schedule = ShowStationActivity.parseSbahnJson(readSbahnFeed);

				for (int i = 0; i < schedule.length; i++) {
					try {
						date1 = sdf
								.parse(schedule[i][6] + " " + schedule[i][2]);
						if (schedule[i][3].equals("")) {
							schedule[i][3] = "0";
						}
						date1.setTime(date1.getTime()
								+ Integer.parseInt(schedule[i][3]) * 60000);
					} catch (ParseException e) {
						// Exception handling goes here
						date1 = currentDate;
						e.printStackTrace();
					}
					// only show future trains
					if ((date1.compareTo(currentDate) >= 0)
							&& (schedule[i][0].contains(sharedPrefs.getString(
									"filter", "")))) {
						col1 = col1 + schedule[i][0] + "\n";
						col2 = col2 + schedule[i][1] + "\n";
						col3 = col3 + schedule[i][2] + "\n";
						col4 = col4 + schedule[i][4] + "\n";
						if (schedule[i][3].equals("0")) {
							col5 = col5 + "\n";
						} else {
							col5 = col5 + "+" + schedule[i][3] + "min\n";
						}

					}

				}
				remoteView.setTextViewText(R.id.widgetHeader, widgetHeader);

				remoteView.setTextViewText(R.id.widgetTextView01, col1);
				remoteView.setTextViewText(R.id.widgetTextView02, col2);
				remoteView.setTextViewText(R.id.widgetTextView03, col3);
				remoteView.setTextViewText(R.id.widgetTextView04, col4);
				remoteView.setTextViewText(R.id.widgetTextView05, col5);
				appWidgetManager.updateAppWidget(appWidgetId, remoteView);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// super.onUpdate(context, appWidgetManager, appWidgetIds);
	}

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		Log.d(LOG_TAG, "onDelete()");

		for (int appWidgetId : appWidgetIds) {

			// stop alarm
			Intent widgetUpdate = new Intent();
			widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
			widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
					appWidgetId);
			widgetUpdate.setData(Uri.withAppendedPath(
					Uri.parse(URI_SCHEME + "://widget/id/"),
					String.valueOf(appWidgetId)));
			PendingIntent newPending = PendingIntent.getBroadcast(context, 0,
					widgetUpdate, PendingIntent.FLAG_UPDATE_CURRENT);

			AlarmManager alarms = (AlarmManager) context
					.getSystemService(Context.ALARM_SERVICE);
			alarms.cancel(newPending);

			// remove preference
			Log.d(LOG_TAG, "Removing preference for id " + appWidgetId);
			SharedPreferences config = context.getSharedPreferences(
					WidgetConfiguration.PREFS_NAME, 0);
			SharedPreferences.Editor configEditor = config.edit();

			configEditor.remove(String.format(
					WidgetConfiguration.PREFS_UPDATE_RATE_FIELD_PATTERN,
					appWidgetId));
			configEditor.commit();
		}

		super.onDeleted(context, appWidgetIds);
	}

	// Fix SDK 1.5 Bug per note here:
	// http://developer.android.com/guide/topics/appwidgets/index.html#AppWidgetProvider
	// linking to this post:
	// http://groups.google.com/group/android-developers/msg/e405ca19df2170e2

	@Override
	public void onReceive(Context context, Intent intent) {

		final String action = intent.getAction();
		Log.d(LOG_TAG, "OnReceive:Action: " + action);
		if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
			final int appWidgetId = intent.getExtras().getInt(
					AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);
			if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
				this.onDeleted(context, new int[] { appWidgetId });
			}
		} else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {

			if (!URI_SCHEME.equals(intent.getScheme())) {
				// if the scheme doesn't match, that means it wasn't from the
				// alarm
				// either it's the first time in (even before the configuration
				// is done) or after a reboot or update

				final int[] appWidgetIds = intent.getExtras().getIntArray(
						AppWidgetManager.EXTRA_APPWIDGET_IDS);

				for (int appWidgetId : appWidgetIds) {

					// get the user settings for how long to schedule the update
					// time for
					SharedPreferences config = context.getSharedPreferences(
							WidgetConfiguration.PREFS_NAME, 0);
					int updateRateSeconds = config
							.getInt(String
									.format(WidgetConfiguration.PREFS_UPDATE_RATE_FIELD_PATTERN,
											appWidgetId), -1);
					if (updateRateSeconds != -1) {
						Log.i(LOG_TAG, "Starting recurring alarm for id "
								+ appWidgetId);
						Intent widgetUpdate = new Intent();
						widgetUpdate
								.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
						widgetUpdate.putExtra(
								AppWidgetManager.EXTRA_APPWIDGET_IDS,
								new int[] { appWidgetId });

						// make this pending intent unique by adding a scheme to
						// it
						widgetUpdate.setData(Uri.withAppendedPath(
								Uri.parse(WidgetProvider.URI_SCHEME
										+ "://widget/id/"),
								String.valueOf(appWidgetId)));
						PendingIntent newPending = PendingIntent.getBroadcast(
								context, 0, widgetUpdate,
								PendingIntent.FLAG_UPDATE_CURRENT);

						// schedule the updating
						AlarmManager alarms = (AlarmManager) context
								.getSystemService(Context.ALARM_SERVICE);
						alarms.setRepeating(AlarmManager.ELAPSED_REALTIME,
								SystemClock.elapsedRealtime(),
								updateRateSeconds * 1000, newPending);
					}
				}
			}
			super.onReceive(context, intent);
		} else {
			super.onReceive(context, intent);
		}
	}
}
